---
import Head from "../components/Head.astro";
import Header from "../components/Header.astro";
import Footer from "../components/Footer.astro";
import { config_site } from "../utils/config-adapter";
import "../styles/global.styl";
import "../styles/layouts/ArchivesLayout.styl";
import dayjs from "dayjs";

interface Props {
  pageTitle: string;
  description: string;
  posts: any[];
  totalPostsCount: number;
  noindex?: boolean;
}

const {
  pageTitle,
  description,
  posts,
  totalPostsCount,
  noindex = true,
} = Astro.props;

// 按年月分组 - This logic now uses the 'posts' prop
const archivesByYearMonth: Record<number, Record<number, any[]>> = {};
posts.forEach((post: any) => {
  if (!post.data.date) return;
  const date = dayjs(post.data.date);
  const year = date.year();
  const month = date.month() + 1; // dayjs 月份从 0 开始
  if (!archivesByYearMonth[year]) {
    archivesByYearMonth[year] = {};
  }
  if (!archivesByYearMonth[year][month]) {
    archivesByYearMonth[year][month] = [];
  }
  archivesByYearMonth[year][month].push(post);
});

// 按年份降序排序 -
const sortedYears = Object.keys(archivesByYearMonth)
  .map(Number)
  .sort((a: number, b: number) => b - a);
---

<!doctype html>
<html lang={config_site.lang}>
  <Head
    title={pageTitle}
    titleTemplate={`%s | ${config_site.title}`}
    description={description}
    author={config_site.author}
    url={config_site.url + "/archives/"}
    canonical={config_site.url + "/archives/"}
    noindex={noindex}
  >
    {/* Allow passing additional head elements if needed */}
    <slot name="head" />
  </Head>
  <body>
    <script>
      import "../scripts/background.ts";
    </script>
    <Header />
    <main class="archives-container">
      <div class="page-header">
        {/* Use a more generic title prop for the H1, description prop for P */}
        <h1 class="page-title">{pageTitle.split(" | ")[0]}</h1>
        <p class="page-description">{description}（共 {totalPostsCount} 篇）</p>
      </div>

      <div class="timeline-container">
        {
          sortedYears.length > 0 ? (
            sortedYears.map((year) => (
              <div class="year-section">
                <div class="year-header">
                  <h2 class="year-title">{year}</h2>
                  <div class="year-count">
                    {Object.values(archivesByYearMonth[year]).flat().length}{" "}
                    篇文章
                  </div>
                </div>
                {Object.keys(archivesByYearMonth[year])
                  .map(Number)
                  .sort((a, b) => b - a) // 月份降序排列
                  .map((month) => (
                    <div class="month-section">
                      <h3 class="month-title">{month}月</h3>
                      <ul class="post-list">
                        {archivesByYearMonth[year][month].map((post) => (
                          <li class="post-item">
                            <div class="post-date">
                              {dayjs(post.data.date).format("YYYY-MM-DD")}
                            </div>
                            <a
                              href={`/posts/${post.data.abbrlink}/`}
                              class="post-link"
                            >
                              {post.data.title}
                            </a>
                          </li>
                        ))}
                      </ul>
                    </div>
                  ))}
              </div>
            ))
          ) : (
            <div class="no-posts">暂无文章</div>
          )
        }
      </div>

      <!-- 懒加载指示器 -->
      <div id="lazyload-observer" class="lazyload-observer">
        <div class="loading-spinner">
          <span class="dot"></span>
          <span class="dot"></span>
          <span class="dot"></span>
        </div>
        <div class="loading-text">加载更多内容</div>
      </div>
      {/* Allow passing additional main content if needed */}
      <slot name="main" />
    </main>
    <Footer />

    <script>
      // 懒加载实现 (This script is identical to the original page's script)
      document.addEventListener("DOMContentLoaded", () => {
        let visibleYears = 2;
        const yearSections = document.querySelectorAll(".year-section");
        const totalYears = yearSections.length;
        const lazyloadObserver = document.getElementById("lazyload-observer");

        const updateLoadingIndicator = (
          isLoading: boolean,
          isComplete: boolean
        ) => {
          if (!lazyloadObserver) return;
          const loadingText = lazyloadObserver.querySelector(
            ".loading-text"
          ) as HTMLElement;
          const loadingSpinner = lazyloadObserver.querySelector(
            ".loading-spinner"
          ) as HTMLElement;
          if (isComplete) {
            if (loadingText) loadingText.textContent = "已加载全部内容";
            if (loadingSpinner) loadingSpinner.style.display = "none";
            setTimeout(() => {
              if (lazyloadObserver) {
                (lazyloadObserver as HTMLElement).style.opacity = "0";
                setTimeout(() => {
                  if (lazyloadObserver) {
                    (lazyloadObserver as HTMLElement).style.display = "none";
                  }
                }, 500);
              }
            }, 3000);
          } else {
            if (loadingText)
              loadingText.textContent = isLoading
                ? "正在加载..."
                : "滚动加载更多";
          }
        };

        const showYearSection = (index: number) => {
          if (index >= 0 && index < totalYears && yearSections[index]) {
            const section = yearSections[index] as HTMLElement;
            section.style.display = "block";
            section.style.opacity = "0";
            setTimeout(() => {
              section.style.opacity = "1";
              section.style.transform = "translateY(0)";
            }, 50);
          }
        };
        if (totalYears > 0) {
          for (let i = 0; i < totalYears; i++) {
            if (i < visibleYears) {
              showYearSection(i);
            } else {
              (yearSections[i] as HTMLElement).style.display = "none";
            }
          }
          if (totalYears <= visibleYears && lazyloadObserver) {
            updateLoadingIndicator(false, true);
          }
        }

        const observer = new IntersectionObserver(
          (entries) => {
            entries.forEach((entry) => {
              if (entry.isIntersecting && visibleYears < totalYears) {
                updateLoadingIndicator(true, false);
                setTimeout(() => {
                  showYearSection(visibleYears);
                  visibleYears++;
                  if (visibleYears >= totalYears) {
                    updateLoadingIndicator(false, true);
                  } else {
                    updateLoadingIndicator(false, false);
                  }
                }, 300);
              }
            });
          },
          {
            rootMargin: "300px",
            threshold: 0.1,
          }
        );

        if (lazyloadObserver) {
          observer.observe(lazyloadObserver);
        } else {
          console.warn("懒加载指示器元素未找到");
        }

        window.addEventListener("error", (e) => {
          if (
            e.message.includes("lazyload") ||
            e.message.includes("observer")
          ) {
            console.error("懒加载功能出现错误:", e);
          }
        });
      });
    </script>
  </body>
</html>
